package com.info.zhiduoduo.core.service.payment.thirdpay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.info.zhiduoduo.common.configs.*;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.pay.PinganPayOrderState;
import com.info.zhiduoduo.common.constants.pay.ZhaoShangPayOrderState;
import com.info.zhiduoduo.common.exception.RollbackException;
import com.info.zhiduoduo.common.utils.LogUtil;
import com.info.zhiduoduo.core.dto.pingan.PinganTransferFormBean;
import com.info.zhiduoduo.core.dto.pingan.SingleTransfer;
import com.info.zhiduoduo.core.dto.pingan.SingleTransferQuery;
import com.info.zhiduoduo.core.service.WxMessageService;
import com.info.zhiduoduo.core.service.ZhiduoduoProjectService;
import com.info.zhiduoduo.repository.entity.order.TradeRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

@Slf4j
@Service
public class PinganPayService implements ThirdPayService {

    @Autowired
    ZhiduoduoProjectService zhiduoduoProjectService;
    @Autowired
    WxMessageService wxMessageService;
    @Autowired
    CommonConfig commonConfig;
    @Autowired
    ZddUrlConfig zddUrlConfig;
    @Autowired
    PayConfig payConfig;
    @Autowired
    KltPayConfig kltPayConfig;
    @Autowired
    PayTestModeConfig payTestModeConfig;

    @Override
    public SmartResult doCallPayApi(TradeRecord tradeRecord) {
        SmartResult smartResult = null;
        // 测试
        if (payTestModeConfig.isTestMode()) {
            // 直接支付成功
            // 等待10秒，模拟超时情况
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
            SingleTransfer singleTransfer = new SingleTransfer();
            singleTransfer.setStt("20");
            singleTransfer.setThirdVoucher(tradeRecord.getTradeno());
            smartResult = SmartResult.success(singleTransfer);
        } else {
            //调用第三方支付
            PinganTransferFormBean formBean = PinganTransferFormBean.of(tradeRecord);
            String url = zddUrlConfig.getBasePayUrl() + payConfig.getPinganSingleTransferUrl();
            LogUtil.info("支付调用 url = " + url);
            smartResult = new RestTemplate().postForObject(url, formBean, SmartResult.class);
        }
        return handlePinganPayResult(tradeRecord, smartResult);
    }

    @Override
    public SmartResult handlePayUserTradeState(TradeRecord trade, String orderState, String errorcode, String errormsg) {
        if (trade == null) return SmartResult.success(StatusMsg.StatusMsg_444);
        trade.setErrorcode(errorcode).setErrormsg(errormsg);
        switch (orderState) {
            case ZhaoShangPayOrderState.SUCCESS:
                trade.setTradestate(Constants.TRADE_SUCCESS).setFinishtime(new Date());
                zhiduoduoProjectService.doAfterPayUserTradeSucceed(trade);
                break;
            case ZhaoShangPayOrderState.FAIL:
                trade.setTradestate(Constants.TRADE_FAIL).setFinishtime(new Date());
                wxMessageService.notifyAdminPaymentFail(trade);
                break;
        }
        if (trade.updateById()) return SmartResult.success();
        return SmartResult.fail(StatusMsg.StatusMsg_445);
    }

    public SmartResult handleUserTradeState(TradeRecord trade, SmartResult smartResult) {
        if (trade == null) return SmartResult.success(StatusMsg.StatusMsg_444);
        if (null != smartResult) {
            trade.setErrorcode(String.valueOf(smartResult.getState())).setErrormsg(smartResult.getMsg());
            if (smartResult.getObject() != null && smartResult.isSuccessful()) {
                SingleTransferQuery transferQuery = JSON.parseObject(JSON.toJSONString(smartResult.getObject()),
                        new TypeReference<SingleTransferQuery>() {
                        });
                if (PinganPayOrderState.SUCCESS.equals(transferQuery.getStt())) {
                    trade.setTradestate(Constants.TRADE_SUCCESS).setFinishtime(new Date());
                    zhiduoduoProjectService.doAfterPayUserTradeSucceed(trade);
                } else if (PinganPayOrderState.FAIL.equals(transferQuery.getStt())) {
                    trade.setTradestate(Constants.TRADE_FAIL).setFinishtime(new Date());
                    wxMessageService.notifyAdminPaymentFail(trade);
                }
            } else {
                trade.setTradestate(Constants.TRADE_FAIL).setFinishtime(new Date());
                wxMessageService.notifyAdminPaymentFail(trade);
            }
        }
        if (trade.updateById()) return SmartResult.success();
        return SmartResult.fail(StatusMsg.StatusMsg_445);
    }

    private SmartResult handlePinganPayResult(TradeRecord trade, SmartResult smartResult) {
        if (null == smartResult) {
            LogUtil.info("zdd-pay没有返回smartResult");
            throw new RollbackException(" 项目,平安支付失败");
        }
        if (smartResult.getObject() == null || smartResult.isFailed()) {
            trade.setTradestate(Constants.TRADE_FAIL).updateById();
            trade.setErrorcode(String.valueOf(smartResult.getState()));
            trade.setErrormsg(smartResult.getMsg());
            if (trade.updateById()) return SmartResult.success();
            return SmartResult.fail(StatusMsg.StatusMsg_445);
        } else {
            //支付接口调用成功,查看交易结果
            SingleTransfer singleTransfer = JSON.parseObject(JSON.toJSONString(smartResult.getObject()), new TypeReference<SingleTransfer>() {
            });
            if (null == singleTransfer || PinganPayOrderState.FAIL.equals(singleTransfer.getStt())) {
                trade.setTradestate(Constants.TRADE_FAIL).setFinishtime(new Date());
                wxMessageService.notifyAdminPaymentFail(trade);
                if (trade.updateById()) return SmartResult.success();
                return SmartResult.fail(StatusMsg.StatusMsg_445);
            } else {
                trade.setPartnerOrderNo(singleTransfer.getThirdVoucher()).setTradestate(Constants.TRADE_IN_PROCESS);
                if (trade.updateById()) return SmartResult.success();
                return SmartResult.fail(StatusMsg.StatusMsg_445);
            }
        }
    }

    @Override
    public SmartResult handlePayJiugeTradeState(TradeRecord trade, String orderState, String errorcode, String errormsg) {
        return SmartResult.fail(StatusMsg.StatusMsg_445);
    }

}
